from django.shortcuts import render
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from django.core.paginator import Paginator


# Create your views here.




class Sgoods_API(APIView):
    def get(self,request):
        g = Sgoods.objects.all()
        cpage = request.GET.get('cpage')
        pag = Paginator(g, 2)
        tpage = pag.page(cpage)
        ser = Sgoods_Ser(tpage, many=True)
        num = pag.num_pages
        return Response({"code": 200, 'list': ser.data, 'num': num})

    def delete(self,request):
        id = request.GET.get('id')
        Sgoods.objects.filter(id=id).first().delete()
        return Response({"code":200})

class Sfenlei_API(APIView):
    def get(self,request):
        id = request.GET.get('id')
        s = Sgoods.objects.filter(id=id).first()
        g = Sgoods.objects.filter(fenlei_id=s.fenlei_id).all()
        ser = Sgoods_Ser(g,many=True)
        return Response({"code":200,'list':ser.data})

class Wenzhang_API(APIView):
    def post(self,request):
        name = request.data.get('name')
        password = request.data.get('password')
        w = Wusers.objects.filter(name=name).first()
        if w:
            if w.password == password:
                return Response({"code":200,'userid':w.id,'mes':"登录成功"})
            else:
                return Response({"code":10010,'mes':'密码错误'})
        else:
            return Response({"code": 10010, 'mes': '用户名不存在'})

    def get(self,request):
        w = Wenzhang.objects.all()
        cpage = request.GET.get('cpage')
        pag = Paginator(w,2)
        tpage = pag.page(cpage)
        ser = Wenzhang_Ser(tpage,many=True)
        num = pag.num_pages
        return Response({"code":200,'num':num,'list':ser.data})

class Pl_API(APIView):
    def post(self,request):
        ser = Pl_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code":10010})

    def get(self,request):
        wenzhang_id = request.GET.get('wenzhang_id')
        pl = Pl.objects.filter(wenzhang_id=wenzhang_id).all()
        ser = Pl_Ser1(pl,many=True)
        return Response({"code":200,"list":ser.data})


















